﻿using System;
using System.Drawing;
using Microsoft.Xna.Framework;
using System.Linq;

using Color = System.Drawing.Color;
using Rectangle = System.Drawing.Rectangle;

namespace MaterialEditor
{
    public class InputSlot
    {
        private NodeValue _value;
        public NodeValue value
        {
            get { return _value; }

            set
            {
                if (_value != null)
                    _value.ValueChanged -= InputSlot_ValueChanged;
                _value = value;
                if (_value != null)
                    _value.ValueChanged += InputSlot_ValueChanged;
                if (ValueChanged != null)
                    ValueChanged();
            }
        }

        public Color color
        {
            get
            {
                if (value == null || connector == null)
                    return Color.Gray;
                return TypeColorLookup.instance[value.type];
            }
        }

        public string name;

        public Node parent;

        private int ParentIndex
        {
            get
            {
                for (int i = 0; i < parent.input.Length; i++)
                    if (parent.input[i] == this)
                        return i;

                throw new InvalidOperationException("What teh feuk!!????");
            }
        }

        private NodeValueType[] AcceptTypes
        {
            get { return parent.acceptTypes[ParentIndex]; }
        }

        public bool isConnected
        {
            get { return _connector != null; }
        }

        public event BasicDelegate Connected;
        public event BasicDelegate Disconnected;
        public event BasicDelegate ValueChanged;

        private NodeConnector _connector;
        public NodeConnector connector
        {
            get { return _connector; }

            set
            {
                _connector = value;
                if (value != null && Connected != null && value.startSlot.value != null && AcceptTypes.Contains(value.startSlot.value.type))
                {
                    this.value = value.Start.output.value;
                    Connected();
                }
                else if (value != null && Disconnected != null)
                {
                    _connector.Disconnect();
                    Disconnected();
                }
            }
        }

        public Vector2 position
        {
            get { return parent.GetInputLocation(this); }
        }

        public Rectangle Rect
        {
            get { return new Rectangle((int)position.X - 3, (int)position.Y - 3, Node.InputSpacing, Node.InputSpacing); }
        }

        public InputSlot(Node parent, NodeValue value, string name)
        {
            this.parent = parent;
            this.value = value;
            this.name = name;
        }

        void InputSlot_ValueChanged()
        {
            if (ValueChanged != null)
                ValueChanged();
        }
    }
}